<?php

namespace Platform\Repository\Organize;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Platform\Models\Organize\Leader;
use Platform\Models\Organize\LeaderRole;
use Platform\Models\Organize\Organize;
use Platform\Repository\Repository;

class OrganizeRepository extends Repository
{

    public function model()
    {
        return  Organize::class;
    }

    /**
     * 创建默认用户
     * @param Organize $organize
     * @return array
     */
    public function createDefaultLeader(Organize $organize)
    {
        $role = $this->createDefaultRole($organize);
        $data = [
            'username' => randomKeys(7,false,true),
            'password' => bcrypt('123456'),
            'name' => '超级管理员',
            'is_organize_admin' => 1,
            'role_id' => $role->id,
            'organize_id' => $organize->id,
        ];

        $organize->leader()->create($data);
        $res = [
            'leader' => [
                'username' => $data['username'],
                'password' => '123456',
            ],
            'role' => [
                'name' => $role->name,
                'describe' => $role->describe,
            ],

        ];
        return $res;
    }

    /**
     * 创建默认角色
     * @param Organize $organize
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function createDefaultRole(Organize $organize)
    {
        $data = [
            'name' => '超级管理员',
            'describe' => '默认角色',
            'is_default' => LeaderRole::DEFAULT_YES,
            'organize_id' => $organize->id,
        ];

        return $organize->role()->create($data);
    }

    /**
     * 获取组织下的超级管理员
     * @param Organize $organize
     * @param Leader|null $leader
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\HasMany|mixed|null|object
     */
    public function getAnotherOrganizeAdmin(Organize $organize, Leader $leader = null)
    {
        return $organize->leader()
            ->where('is_organize_admin',1)
            ->when($leader,function ($query,$leader){
                return $query->where('id','<>',$leader->id);
            })
            ->first();
    }

    /**
     * 通过关键词查询
     * @param Request $request
     * @return Builder
     */
    public function screen(Request $request){
        $builder = $this->model->newQuery();

        $name = $request->get('name',null);
        $begin_at = $request->get('begin_at',null);
        $end_at = $request->get('end_at',null);

//        $builder->with('role');

        if ($name){
            $builder->where('name', 'like', '%'.$name.'%');
        }
        if ($begin_at){
            $builder->whereDate('created_at', '>=', $begin_at);
        }
        if ($end_at){
            $builder->whereDate('created_at', '<=', $end_at);
        }

        return $builder->paginate(10);
    }


}
